//
//  BBSimpleObjectServer.m
//  BBTouch
//
//  Created by ben smith on 7/29/08.
//  This file is part of BBTouch.
//
//  BBTouch is free software: you can redistribute it and/or modify
//  it under the terms of the GNU Lesser General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.

//  BBTouch is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU Lesser General Public License for more details.

//  You should have received a copy of the GNU Lesser General Public License
//  along with BBTouch.  If not, see <http://www.gnu.org/licenses/>.
// 
//  Copyright 2008 Ben Britten Smith ben@benbritten.com .
//

#import "BBSimpleObjectServer.h"


@implementation BBSimpleObjectServer
+(BBSimpleObjectServer*)defaultServerOnPort:(int)portnum
{
	BBSimpleObjectServer * newServer = [[BBSimpleObjectServer alloc] init];
	[newServer startListeningOnPort:4333];
	return [newServer autorelease];
}

-(void)startListeningOnPort:(int)portnum
{
	// initialize server with dist obj
	clients = [[NSMutableDictionary alloc] initWithCapacity:10];
	
	NSSocketPort  *port = [[NSSocketPort alloc] initWithTCPPort:portnum];
	connection = [[NSConnection alloc] initWithReceivePort:port sendPort:nil];

  [connection setRootObject:self];
	
  if ([connection registerName:@"BBTouchObjectServer"] == NO) {
		NSLog(@"Failed to register name");
		return;
  } 
	
  [[NSNotificationCenter defaultCenter] addObserver:self
																					 selector:@selector(connectionDidDie:)
																							 name:NSConnectionDidDieNotification
																						 object:connection];
	
  [[NSNotificationCenter defaultCenter] addObserver:self
																					 selector:@selector(connectionInitialized:)
																							 name:NSConnectionDidInitializeNotification
																						 object:connection];
	
	
	[connection retain];
	[connection setDelegate:self];		
}

- (void) connectionDidDie:(id)val ;
{
	NSLog(@"Connection Died!!");
}

- (void) connectionInitialized:(id)val;
{
	NSLog(@"Connection Initialized!");
}

- (BOOL) registerClient: (byref id)client withName:(bycopy NSString *) name
{
	//[clients setObject:client forKey:name];
//	[client sendMessageToClient:[NSDictionary dictionaryWithObject:@"successful registration" forKey:@"note"]];
	return YES;
}

- (BOOL) unregisterClientWithName: (bycopy NSString *) name
{
	//[clients removeObjectForKey:name];
	return YES;
}

- (BOOL) sendMessageToServer:(bycopy NSString *)msg
{
	NSLog(@"sendMessageToServer: %@",msg);
	return YES;
}



@end
